<template>
  <div id="map"></div>
</template>
<script>
import Map from "ol/Map.js";
import View from "ol/View.js";
import TileLayer from "ol/layer/Tile.js";
import { fromLonLat } from "ol/proj.js";
import OSM from "ol/source/OSM.js";
import XYZ from "ol/source/XYZ.js";

export default {
  mounted () {
    var roads = new TileLayer({
      source: new OSM({
        url: "http://tile-{a-c}.openstreetmap.fr/hot/{z}/{x}/{y}.png" //osm地形
      })
    });

    var imagery = new TileLayer({
      source: new XYZ({
        url: "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=76d35ea95dafb0023ee631a25e260ec4" //天地图影像
      }),
      projection: "EPSG:4326"
    });

    var container = document.getElementById("map");

    var map = new Map({
      layers: [roads, imagery],
      target: container,
      view: new View({
        center: fromLonLat([114, 30]),
        zoom: 12
      })
    });

    var radius = 75;
    document.addEventListener("keydown", function(evt) {
      if (evt.which === 38) {
        radius = Math.min(radius + 5, 150);
        map.render();
        evt.preventDefault();
      } else if (evt.which === 40) {
        radius = Math.max(radius - 5, 25);
        map.render();
        evt.preventDefault();
      }
    });

    // get the pixel position with every move
    var mousePosition = null;

    container.addEventListener("mousemove", function(event) {
      mousePosition = map.getEventPixel(event);
      map.render();
    });

    container.addEventListener("mouseout", function() {
      mousePosition = null;
      map.render();
    });

    // before rendering the layer, do some clipping
    imagery.on("precompose", function(event) {
      var ctx = event.context;
      var pixelRatio = event.frameState.pixelRatio;
      ctx.save();
      ctx.beginPath();
      if (mousePosition) {
        // only show a circle around the mouse
        ctx.arc(
          mousePosition[0] * pixelRatio,
          mousePosition[1] * pixelRatio,
          radius * pixelRatio,
          0,
          2 * Math.PI
        );
        ctx.lineWidth = 5 * pixelRatio;
        ctx.strokeStyle = "rgba(0,0,0,0.5)";
        ctx.stroke();
      }
      ctx.clip();
    });

    // after rendering the layer, restore the canvas context
    imagery.on("postcompose", function(event) {
      var ctx = event.context;
      ctx.restore();
    });
  }
};
</script>

<style scoped>
</style>
